/*-------------------------------------------------------*/
/*                                                       */
/* Some STUFF nobody knows where to put.                 */
/* This STUFF is [c]copyright by AlphaHelix.             */
/* In the year of 1996 (actually in May).                */
/*                                                       */

#include <stdlib.h>
#include <string.h>

#include "xlib.hpp"
#include "sound.hpp"
#include "ravage.hpp"


#define FADESPEED       2


/*---------------------------------------------------------
 Function:

 Description:
 Fadeout screen and\or sound.
 No game update will be done during fadeout.
---------------------------------------------------------*/
void fadeout(int mode)
{
   int   i;
   int   mod_vol;

// Setup palette fading if required.
   if (mode & FADE_PALETTE) {
      palette.unlock();
      palette.fade(0, 0, 0, FADESPEED);
   }
// Get current music volume,
   mod_vol = s_getmodvol() - 1;
   if (mod_vol <= 0) mode &= ~FADE_MUSIC;
// Synchronize to timer. (We want a good start.)
   timer_ticks = 0; while(!timer_ticks);
// Do fading. This requires us to do 64 steps.
   for (i = 64; i >= 0; i-=FADESPEED) {
// Do palette fading.
      doeffects();
// Do sound fading.
      if (mode & FADE_MUSIC) s_setmodvol((mod_vol*i)/64 + 1);
// Sync to timer.
      while(!timer_ticks); timer_ticks = 0;
   }
   if (mode & FADE_PALETTE) palette.lock();
// Completly stop playing mode and restore old music volume.
   if (mode & FADE_MUSIC) {
      s_stopmod();
      s_setmodvol(mod_vol + 1);
   }
}

void fadein(void *p)
{
   palette.unlock();
   palette.calcshadows(p, DEEPSHADOW);
   palette.fade(p, FADESPEED);
   timer_ticks = 0; while(!timer_ticks);
   while (palette.isfading()) {
      while(!timer_ticks); timer_ticks = 0;
      doeffects();
   }
   palette.lock();
}


//--------------------------------------------------------
// Beautiful write.
//--------------------------------------------------------

void beauty(Font *font, int &x, int &y, char *text)
{
   static char     word[80];
   int    color;
   int    tmp;

   while (*text) {
      sscanf(text, "%s", word);
      if (font->textlen(word)+x > XMAX-10) {
         if (*text == ' ') text++;
         x = 0; y += font->height() + 1;
      }
      switch (*text) {
      case '^':
         switch (text[1]) {
         case 'c':
            color = (text[2]-'0')*100 + (text[3]-'0')*10 + (text[4]-'0');
            text += 5;
            break;
         case 's':
            tmp = (text[2]-'0')*10 + (text[3]-'0');
            x += tmp * (font->charlen(' ') + 1);
            text += 4;
            break;
         case 'e':
            return;
         }
         break;
      case 0x0a:
      case 0x0d:
         x = 0; y += font->height() + font->height()/2;
         text += 2;
         break;
      default:
         font->vanilla_char(x, y, *text, color);
         x += font->charlen(*text);
         text++;
      }
   }
}


